package cn.com.sise.servlet;

import cn.com.sise.entity.Book;
import cn.com.sise.service.IBookService;
import cn.com.sise.service.impl.BookServiceImpl;
import cn.com.sise.utils.MyUtil;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/addBook")
@MultipartConfig
public class AddBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.收集图书信息，将所获取到的信息封装到Book类的实例中
        //2040706301- 雷诏华
        Book book = new Book();
        long time = new Date().getTime();
        String id = String.valueOf(time);
        id=id.substring(id.length()-5,id.length());
        request.setCharacterEncoding("UTF-8");
        book.setId(Integer.parseInt(id));
        book.setAuthor(request.getParameter("author"));
        book.setName(request.getParameter("name"));
        book.setPrice(Float.parseFloat(request.getParameter("price")));
        book.setPress(request.getParameter("press"));
        book.setISBN(request.getParameter("ISBN"));
        Part part = request.getPart("pic");
        String fileName=null;
        if (part!=null){
            fileName = MyUtil.getFileName(part);
        }
        book.setPic(fileName);
        File uploadFile = new File("F:\\code\\java\\javaweb\\javaee\\lab10\\web\\uploadFile");
        System.out.println();
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        //2.上传图片到E：\pic
        if (fileName != null) {
            part.write(uploadFile+File.separator+fileName);
        }

        //3.调用BookServiceImpl的add方法将图书信息添加到数据库中
        IBookService bookService=new BookServiceImpl();
        try {
            int result=bookService.add(book);
            if (result==0){
                System.out.println("图书添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        //4.页面重定向到/showAllBooksServlet
        response.sendRedirect("showAllBooksServlet");
    }

}
